/**
 * Created by user on 15-11-22.
 */
var request = require('request')
    , URL = require('url')
    , Promise = require('bluebird')
    , Request = Promise.promisify(require("request"))
    , fs = Promise.promisifyAll(require("fs"))
    , config = require('../config.js').Config
    , Models = require('../lib/models.js')
    , Point = Models.point()
    , _ = require('lodash')
    , count = 0
    , arr = [{num: "MA0", name: "甲醇"}, {num: "PP0", name: "聚丙烯"}]

function RequestSina(name) {
    var url = "http://stock.finance.sina.com.cn/futures/api/json.php/InnerFuturesService.getInnerFuturesDailyKLine?symbol=" + name
    return new Promise(function (resolve, reject) {
        Request.get({url: url}, function (err, res, body) {
            if (!err && res.statusCode == 200) {
                resolve(body)
            } else {
                reject(err)
            }
        })
    })
}


Promise.resolve()
    .then(function () {
        return Promise.map(arr, function (obj) {
            var promise = []
                , name = obj.name
                , num = obj.num
            return RequestSina(num)
                .then(function (data) {
                    data = eval('(' + data + ')')
                    console.log(data.length)
                    data.forEach(function (pointObj) {
                        promise.push(Point.Qadd(0, num, name, pointObj.open, pointObj.close, pointObj.high, pointObj.low, pointObj.volume, pointObj.date))
                    })
                    return Promise.all(promise)
                })
        })
    }).then(function () {
        process.exit(0)
    }).catch(function (err) {
        console.trace(err)
        process.exit(0)
    })